package com.oa.tools.jobs.impl;

import java.util.List;
import java.util.Map;

import com.oa.tools.TkMapper;
import com.oa.tools.entity.FlowLog;
import com.oa.tools.entity.OAFlowInstanceWithBLOBs;
import com.oa.tools.jobs.FlowHandlerTaskBase;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.http.EKPRequestClient;

import tk.mybatis.mapper.entity.Example;

public class AddNewCYCPeopleTask extends FlowHandlerTaskBase{

	
	public AddNewCYCPeopleTask(Map<String,TkMapper<?>> daoMap) {
		super(daoMap);
		
		this.flowStatus = FlowHandlerTaskBase.FLOW_STATUS_ING;
		this.templateId = "16483820fdacffda7ffbd4146d7ad3a1";
	}

	@Override
	public String exec(boolean notice, OAFlowInstanceWithBLOBs obj) throws Exception {
		String fdId = obj.getFdId();
		Example example_log = new Example(FlowLog.class);
		example_log.createCriteria().andEqualTo("fdProcessId", fdId).andEqualTo("fdFactNodeId", "N35");
		List<FlowLog> flowLogs = this.flowLogDAO.selectByExample(example_log);
		if(flowLogs==null || flowLogs.size()==0) {
			return null;
		}else {
			for(FlowLog flowLog:flowLogs) {
				if(!flowLog.getFdStatus().equals(FlowHandlerTaskBase.FLOW_STATUS_DONE)) {
					return null;
				}
			}
		}
		
		String xmlStr = obj.getExtendDataXml();
//		System.out.println(xmlStr);

		Object [] result = EKPRequestClient.createNewStaffAccountCore(xmlStr, obj.getFdId(),orgElementDAO);

		if (result == null) {
			return obj.getFdId() + "流程已处理:\r\n" + xmlStr;
		}

		obj.setExtendDataXml((String) result[0]);
		this.oAFlowInstanceDAO.updateByPrimaryKeySelective(obj);//updateByPrimaryKeyWithBLOBs(obj);

		StringBuilder mailContent = new StringBuilder();
		mailContent.append("<pre>创建邮箱和OA账号成功日志如下：\r\n");
		List<List<String>> datas = (List<List<String>>) result[1];
		for(List<String> data:datas) {
			mailContent.append(data);mailContent.append("\r\n");
		}
		mailContent.append("</pre><br/>");
		if(result[2]!=null||result[2].toString().trim().length()>0) {
			mailContent.append("<h1 style='color:red;'>"+result[2]+"</h1>");
		}
		String content = mailContent.toString();
		
		

		if (true) {
			String [] receiveMailAccounts = SysConfig.getSysSet("邮箱管理员接收邮箱").toArray(new String[0]);
			MailUtil.sendMail(receiveMailAccounts,
					"工作邮箱和OA账号创建成功", content);
		}

		return content;
	}

	
}
